package com.hxkj.client.service.taglib.directive;

import com.github.pagehelper.PageInfo;
import com.hxkj.client.service.ArticleServiceClient;
import com.hxkj.domain.context.EnvironmentContextHolder;
import com.hxkj.domain.po.Article;
import com.platform.common.domain.result.ParameterDataStruct;
import com.platform.common.domain.to.PageTo;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ArticleListDirective
 * @Description TODO
 * @Author huangzhaoyong
 * @Date 2018/9/28 11:18
 * @Version 1.0
 */
@Slf4j
@Component
public class OverallNewestArticleDirective extends AbstractDirective {

    @Autowired
    private ArticleServiceClient articleServiceClient;


    @Value("${cms.realPath}")
    private String Path;

    /**
     * 输入参数:每页条数
     */
    public static final String COUNT = "count";
    /**
     * 输入参数:开始页数
     */
    public static final String START = "start";
    /**
     * 输出参数：当前分类的文章列表
     */
    public static final String OUTPUT_ARTICLE_LIST = "outputArticleList";


    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        try {
            Integer count = super.getInt(COUNT, params);
            if(null == count){
                count = 5;
            }
            Integer start = super.getInt(START, params);
            if(null == start){
                start = 1;
            }

            //登录token
            String userToken = super.getUserToken(env);
            //是否可视化
            boolean noteNotBlank = StringUtils.isNotBlank(super.getNote(env));
            //组装数据
            assemble(env, start, count, noteNotBlank);

            if(null == body){
                log.debug("分类所在模板至少要加一个空格");
            }

            if (noteNotBlank) {
                //可视化
                super.print(body, params, env, userToken, params);
            }else{
                body.render(env.getOut());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 组装数据
     * @param env
     * @param start
     * @param count
     * @param noteNotBlank
     * @throws Exception
     */
    private void assemble(Environment env, Integer start, Integer count, boolean noteNotBlank) throws Exception {
        //分页
        PageTo pageParam = new PageTo();
        pageParam.setPageNum(start);
        pageParam.setPageSize(count);
        //过滤参数
        Article articleParams = new Article();
        articleParams.setDelTag(0);
        articleParams.setAuditType(0);
        //查询
        ParameterDataStruct<Article> parameterDataStruct = new ParameterDataStruct<>();
        parameterDataStruct.setData(articleParams);
        parameterDataStruct.setPageTo(pageParam);
        PageInfo<Article> resultPageStruct = articleServiceClient.getAllArticleList(parameterDataStruct);
        List<Article> articleList = resultPageStruct.getList();
        if (noteNotBlank) {
            //可视化
            for (Article article : articleList) {
                article.setManuscriptPath(Path + article.getManuscriptPath());
            }
        }else {
            Map<String, Object> enviroment = EnvironmentContextHolder.getEnvironment();
            Map<Long, String> siteCtxMap = (Map<Long, String>) enviroment.get("siteCtxMap");
            // 静态文件文章链接加前缀
            for (Article item : articleList) {
                String urlContext = siteCtxMap.get(item.getSiteId());
                if(StringUtils.isNotBlank(urlContext)) {
                    item.setManuscriptPath(urlContext + item.getManuscriptPath());
                }
            }
        }
        //输出数据
        env.setVariable(OUTPUT_ARTICLE_LIST, DefaultObjectWrapperBuilderFactory.getDefaultObjectWrapper().wrap(articleList));
    }
}
